package util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import sun.misc.BASE64Encoder;

public class MD5Util {
	
	static {
        //添加安全算法提供者
        Security.addProvider(new BouncyCastleProvider());
    }
    
    /**
     * 将传入的字符串用MD5算法进行加密
     * @param pStrPW 需要加密的字符串
     * @return 加密后的字符串
     */
    public static String crypt(String pStrPW){
        String strCrypt = "";
    	if(pStrPW == null || pStrPW.equals("")){ //如果传入参数为空，则返回空字符串
    		return strCrypt;
    	}
        try {
            // Get a MessageDigest object
            MessageDigest md = MessageDigest.getInstance("MD5");

            byte[] data = pStrPW.getBytes();
            int l = data.length;
            for (int i = 0; i < l; i++)
                md.update(data[i]);
            byte[] digest = md.digest();

            strCrypt = new BASE64Encoder().encode(digest);
        } catch (NoSuchAlgorithmException nsae) {
        	System.out.println("MD5算法加密失败"+nsae.getMessage());
        }
        return strCrypt;
    }
    
    public static void main(String[] args){
    	System.out.println(crypt("123456"));		
    }
}
